<?php

namespace app\modules\controllers;

use app\modules\models\blog\BlogModel;
use yii\data\Pagination;
use yii\helpers\Url;
use yii\web\Controller;
use Yii;

class CommonController extends Controller
{
    public $layout = 'layout1';
    protected $actions = ['*'];
    protected $except = [];
    protected $mustlogin = [];

    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'user' => 'admin',
                'only' => $this->actions,
                'except' => $this->except,
                'rules' => [
                    [
                        'allow' => false,
                        'actions' => empty($this->mustlogin) ? [] : $this->mustlogin,
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                        'actions' => empty($this->mustlogin) ? [] : $this->mustlogin,
                        'roles' => ['@'],
                    ],
                ],
            ],

        ];
    }

    //权限使用
    public function beforeAction($action)
    {
        if (!Yii::$app->request->isAjax) {
            if (!parent::beforeAction($action)) {
                return false;
            }
        }
        $controller = $action->controller->id;
        $actionName = $action->id;
        if (Yii::$app->admin->can($controller. '/*')) {
            return true;
        }
        if (Yii::$app->admin->can($controller. '/'. $actionName)) {
            return true;
        }
        throw new \yii\web\UnauthorizedHttpException('对不起，您没有访问'. $controller. '/'. $actionName. '的权限');
        //return true;
    }

    public function init()
    {
        // var_dump(Yii::$app->controller);//没办法拿到controller对象
        // exit;
        // 获取当前用户要访问的控制器名称和方法名称index.php?r=admin/user/del
        // category/* caretory/add
        /*if (Yii::$app->session['admin']['isLogin'] != 1) {
            return $this->redirect(['/admin/public/login']);
        }*/
    }

    public function pageurl($action){
        $page_param=Yii::$app->request->queryString;
        $arr_url=explode('&',$page_param);
        foreach ($arr_url as $k=>$v){
            if(strpos($v,'per-page')!==false){
                unset($arr_url[$k]);
            }
        }
        $pageurl= Url::to([$action]).'?'.implode('&',$arr_url).'&per-page=';
        return $pageurl;
    }

    public function pagesize($code){
        $size=Yii::$app->request->get('per-page');
        if(isset($size)&&!empty($size)){
            $_SESSION[$code]=$size;
            $new_size=$_SESSION[$code];
        }else{
            if($_SESSION[$code] ==null){
                $new_size=Yii::$app->params['pageSize']['common'];
            }else{
                $new_size=$_SESSION[$code];
            }
        }
        return $new_size;
    }




}